#include <QTextStream>
#include <stdio.h>
#include "serial_opt.h"
#include <QDebug>
#include <QList>
#include <QTime>

#include "mainwindow.h"

serial_opt::serial_opt(char *name,int rate)
{

    m_name = QString(name);
    m_baundrate = rate;
}

int serial_opt::show()
{
    qDebug()<<"serial port:"<<this->m_name<<" bundrate:"<<this->m_baundrate;
    return 0;
}

bool serial_opt::open()
{
    port = new QSerialPort();
    port->setPortName("COM3");
    if(port->open(QIODevice::ReadWrite)){
        qDebug()<< "Open serial port successful";
    }else{
        qDebug()<< "Open Serial port failed";
    }
    port->setBaudRate(m_baundrate);
    port->setDataBits(QSerialPort::Data8);

    QObject::connect(port,&QSerialPort::readyRead,this,&serial_opt::Read_Data);

    return true;
}

void serial_opt::Read_Data()
{
    QByteArray buf;
    buf = port->readAll();
    if(!buf.isEmpty()){
        QString str(buf);

        receive_data += str;

        //qDebug()<<receive_data;
        int start = receive_data.indexOf("%factory test%",0);
        if(start != -1){
            //qDebug()<<"Found %%factory test%% :"<<start;
            int end = receive_data.indexOf("\n",start);
            if(end != -1){
                QString line = receive_data.mid(start,end-start);
                qDebug()<<line;

            }
            receive_data = receive_data.mid(end+1);
        }else{
            int point = receive_data.indexOf("\n",0);
            if(point != -1){
                //qDebug()<<point<<"lengh:"<<receive_data.length();
                receive_data = receive_data.mid(point+1);
                //qDebug()<<"***"<<receive_data;
            }

        }

        //qDebug()<<receive_data;
    }
}



